/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.cx1.service.utils.scheduled;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.TimerTask;
import org.apache.commons.lang.StringUtils;
import org.cx1.model.Featured;
import org.cx1.model.Listing;
import org.cx1.model.User;
import org.cx1.model.utils.ServiceResponse;
import org.cx1.service.api.IEmailService;
import org.cx1.service.api.IFeaturedService;
import org.cx1.service.api.IListingService;
import org.cx1.service.api.IUserService;
import org.cx1.service.impl.DFeaturedService;
import org.cx1.service.impl.DListingService;
import org.cx1.service.impl.DUserService;
import org.cx1.service.impl.MEmailService;

/**
 *
 * @author ECH
 */
public class TKSendListingBoost extends TimerTask {
    
    private IListingService listingService = new DListingService();
    private IUserService userService = new DUserService();
    private IFeaturedService featuredService = new DFeaturedService();    
    private IEmailService emailService = new MEmailService();    
    
    private Date lastRun = new Date();
    
    @Override
    public void run() {
        //CX: set once
        featureds = featuredService.readAll(0, 0).getResponse();
        
        setLastRun(new Date());
        
        ServiceResponse<List<User>> response1 = userService.readAll(0, 0);
        List<User> users = response1.getResponse();
        
        if (users != null && users.size() > 0) {
            for (User user : users) {                
                ServiceResponse<List<Listing>> response2 = listingService.readUserListings(user.getId(), 0, 0);
                List<Listing> listings = response2.getResponse();
                
                if (listings != null && listings.size() > 0) {                    
                                        
                    //CX: get candidate listings, 0 to 7 
                    List<Listing> candidateListings = new ArrayList<Listing>();                    
                    for (Listing listing : listings) {  
                        int diffInDays = (int)( (listing.getPostDate().getTime() - (new Date()).getTime()) / (1000 * 60 * 60 * 24) );
                        diffInDays = diffInDays * -1;             
                        
                        if (diffInDays >= 0 && diffInDays <= 7) {
                            if (!checkIfFeatured(listing)) {
                                System.out.println("CX: boost candidate- " + listing.getId() + " - " + listing.getPostDate());  
                                candidateListings.add(listing); 
                            }
                        }                  
                    } 
                    
                    //CX: get random listings
                    List<Listing> randomListings = new ArrayList<Listing>();
                    if (candidateListings.size() > 0) {
                        randomListings = getRandomListings(1, candidateListings);
                    }
                    
                    //CX: dispatch email
                    if (randomListings != null && randomListings.size() > 0) {
                        for (Listing listing : randomListings) {
                            String listingID = listing.getId();
                            String listingTitle = listing.getDisplayTitle();
                            String name = user.getFirstName();
                            String email = user.getEmail();

                            System.out.println("CX: " + listingID + " - " + name + " - " + listingTitle + " - " + email + " ");
                            emailService.sendListingBoost(listingID, listingTitle, name, email);  
                        }
                    }
                }
            } 
        }
    }

    private List<Featured> featureds = new ArrayList<Featured>(0);
    
    private boolean checkIfFeatured(Listing listing) {
        boolean isFeatured = false;        
        if (featureds != null && featureds.size() > 0) {
            for (Featured featured : featureds) {
                if (StringUtils.equalsIgnoreCase(featured.getListingID(), listing.getId())) {
                    isFeatured = true;
                }                
            }
        }
        return isFeatured;
    }
    
    
    private static Random rnd = new Random();

    private List<Listing> getRandomListings(int num, List<Listing> listings) {
        List<Listing> randomListings = new ArrayList<Listing>();
        
        if (listings != null && listings.size() > 0) {
            if (listings.size() <= 2) {
                randomListings.addAll(listings);
            }
            else {
                //CX: get 2 random listings
                Set<Integer> indexes = randomSample(listings.size(), num);
                for (int index : indexes) {
                    randomListings.add( listings.get(index) );
                }
            }
        }
        return randomListings;
    }
    
    public static Set<Integer> randomSample(int n, int m){
        HashSet<Integer> res = new HashSet<Integer>(m);
        for(int i = n - m; i < n; i++){
            int item = rnd.nextInt(i + 1);
            if (res.contains(item))
                res.add(i);
            else
                res.add(item); 
        }
        return res;
    }
        
    
    
    public Date getLastRun() {
        return lastRun;
    }

    public void setLastRun(Date lastRun) {
        this.lastRun = lastRun;
    }
    
    public static void main(String[] argv) {
        Set<Integer> indexes = TKSendListingBoost.randomSample(3, 2);
        for (int index : indexes) {
            System.out.println("CX: " + index);
        }
    }
}
